﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Aliyun.OSS;
using Micro.Core.FrameWork.Config;

namespace Micro.Core.FrameWork.Upload
{
    /// <summary>
    /// 阿里云文件帮助类
    /// </summary>
    public class OssHelper
    {
        private readonly BaseAppConfig _baseAppConfig;
        public OssHelper(BaseAppConfig baseAppConfig) => _baseAppConfig = baseAppConfig;

        /// <summary>
        /// 简单上传文件
        /// </summary>
        /// <param name="vs"></param>
        /// <param name="newName"></param>
        /// <returns></returns>
        public async Task<string> Upload(byte[] vs, string newName)
        {
            // 创建OssClient实例。
            var client = new OssClient(_baseAppConfig.OssInfOssConfig.EndPoint, _baseAppConfig.AccessKeyId, _baseAppConfig.AccessKeySecret);
            try
            {
                MemoryStream requestContent = new MemoryStream(vs);
                // 上传文件。
                var response = client.PutObject(_baseAppConfig.OssInfOssConfig.BucketName, newName, requestContent);

                if (response.HttpStatusCode != HttpStatusCode.OK)
                    throw new Exception($"OOS文件简单上传失败，错误码：{response}、内容：{JsonSerializer.Serialize(response.ResponseStream)}");

                return JsonSerializer.Serialize(response.ResponseStream);
            }
            catch (Exception ex)
            {
                Console.WriteLine("Put object failed, {0}", ex.Message);
                return ex.Message;
            }
        }
    }
}
